package com.bxg.lts;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/*
* 聊天室
*
* */
public class LtsServer {
    public static void main(String[] args) throws IOException {
        //1.创建通道
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        //2.绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(9999));
        //3.设置通道为非阻塞
        serverSocketChannel.configureBlocking(false);
        //4.选择器
        Selector selector = Selector.open();
        //5.将通道绑定到选择器上
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
        //聊天室已创建完成
        System.out.println("java讨论组成立啦!");
        //6.监听
        listen(selector);

    }
    //6.监听,根据客户端的不同状态,不同的处理逻辑
    public static void listen(Selector selector) throws IOException {
        while (true) {
            //获取该选择器上的监听的个数
            int count = selector.select();
            if (count != 0) {
                //获取选择器上所有的令牌
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                //循环遍历
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    //客户端已经连接成功过了,其实就是准备工作
                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                        //设置客户端的延申通道
                        SocketChannel socketChannel = ssc.accept();
                        //设置非阻塞
                        socketChannel.configureBlocking(false);
                        //将通道绑定到选择器上
                        socketChannel.register(selector, SelectionKey.OP_READ);

                        //向客户端发送数据  欢迎语
                        //缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.wrap("欢迎来到聊天室,请输入你的昵称".getBytes());
                        socketChannel.write(byteBuffer);

                    } else if (selectionKey.isReadable()) {
                        //获取通道
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        //缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int len;
                        while ((len = socketChannel.read(byteBuffer)) > 0) {
                            byteBuffer.flip();
                            System.out.println(new String(byteBuffer.array(), 0, len));
                            byteBuffer.clear();
                        }
                    }

                }
            }
        }
    }



}
